package Pet.Management.controller;

import Pet.Management.common.utils.JwtUtils;
import Pet.Management.common.utils.CaptchaUtils;
import Pet.Management.domain.entity.User;
import Pet.Management.domain.vo.LoginRequest;
import Pet.Management.domain.vo.LoginResponse;
import Pet.Management.domain.vo.CaptchaResponse;
import Pet.Management.service.UserService;
import Pet.Management.service.CaptchaService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

@RestController
@CrossOrigin  // 允许跨域请求
public class AuthController {
    
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    
    @Autowired
    private CaptchaService captchaService;

    @GetMapping("/captchaImage")
    public CaptchaResponse getCaptcha() {
        try {
            // 生成验证码文本
            String code = defaultKaptcha.createText();
            // 生成uuid
            String uuid = UUID.randomUUID().toString();
            // 将验证码存入数据库
            captchaService.setCaptchaCode(uuid, code);
            // 生成验证码图片的base64编码
            String base64Image = CaptchaUtils.generateBase64Image(defaultKaptcha, code);
            
            return new CaptchaResponse()
                    .setUuid(uuid)
                    .setImg(base64Image);
        } catch (Exception e) {
            logger.error("生成验证码失败", e);
            throw e;
        }
    }

    @PostMapping("/login")
    public LoginResponse login(@Valid @RequestBody LoginRequest request) {
        try {
            logger.info("登录请求：{}", request);
            
            // 验证码校验
            String code = captchaService.getCaptchaCode(request.getUuid());
            if (code == null) {
                logger.warn("验证码已过期, uuid: {}", request.getUuid());
                return new LoginResponse()
                    .setCode(500)
                    .setMsg("验证码已过期");
            }
            if (!code.equalsIgnoreCase(request.getCode())) {
                logger.warn("验证码错误, 输入: {}, 正确: {}", request.getCode(), code);
                return new LoginResponse()
                    .setCode(500)
                    .setMsg("验证码错误");
            }
            // 删除验证码
            captchaService.deleteCaptchaCode(request.getUuid());
            
            // 登录验证
            User user = userService.login(request.getUsername(), request.getPassword());
            
            // 验证用户是否存在和密码是否正确
            if (user == null) {
                logger.warn("用户名或密码错误: {}", request.getUsername());
                return new LoginResponse()
                    .setCode(500)
                    .setMsg("账号或密码错误");
            }
            
            // 生成token
            String token = jwtUtils.generateToken(user.getUsername(), user.getId());
            logger.info("生成token: {}", token);
            
            // 构建响应
            LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
            userInfo.setUserId(user.getId());
            userInfo.setUserName(user.getUsername());
            userInfo.setNickname(user.getNickname());
            userInfo.setAvatar(user.getAvatar());
            userInfo.setEmail(user.getEmail());
            userInfo.setPhone(user.getPhone());
            userInfo.setStatus(user.getStatus());
            userInfo.setIsAdmin(user.getIsAdmin());
            userInfo.setRoles(user.getRoles());
            userInfo.setPermissions(user.getPermissions());
            
            // 转换角色和权限为List
            List<String> rolesList = user.getRoles() != null ? Arrays.asList(user.getRoles()) : new ArrayList<>();
            List<String> permissionsList = user.getPermissions() != null ? Arrays.asList(user.getPermissions()) : new ArrayList<>();
            
            return new LoginResponse()
                    .setCode(200)
                    .setMsg("登录成功")
                    .setToken(token)
                    .setUser(userInfo)
                    .setRoles(rolesList)
                    .setPermissions(permissionsList);
        } catch (Exception e) {
            logger.error("登录失败", e);
            // 返回用户友好的错误信息，而不是抛出异常
            return new LoginResponse()
                .setCode(500)
                .setMsg("登录失败: " + e.getMessage());
        }
    }

    @GetMapping("/getInfo")
    public LoginResponse getInfo(@RequestHeader("Authorization") String token) {
        try {
            logger.info("获取用户信息, token: {}", token);
            
            // 处理Bearer token
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            if (!jwtUtils.validateToken(token)) {
                logger.warn("token无效: {}", token);
                return new LoginResponse()
                    .setCode(401)
                    .setMsg("token无效");
            }
            
            // 获取用户信息
            Long userId = jwtUtils.getUserIdFromToken(token);
            User user = userService.getById(userId);
            
            if (user == null) {
                logger.warn("用户不存在, id: {}", userId);
                return new LoginResponse()
                    .setCode(401)
                    .setMsg("用户不存在");
            }
            
            // 构建响应
            LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
            userInfo.setUserId(user.getId());
            userInfo.setUserName(user.getUsername());
            userInfo.setNickname(user.getNickname());
            userInfo.setAvatar(user.getAvatar());
            userInfo.setEmail(user.getEmail());
            userInfo.setPhone(user.getPhone());
            userInfo.setStatus(user.getStatus());
            userInfo.setIsAdmin(user.getIsAdmin());
            userInfo.setRoles(user.getRoles());
            userInfo.setPermissions(user.getPermissions());
            
            // 转换角色和权限为List
            List<String> rolesList = user.getRoles() != null ? Arrays.asList(user.getRoles()) : new ArrayList<>();
            List<String> permissionsList = user.getPermissions() != null ? Arrays.asList(user.getPermissions()) : new ArrayList<>();
            
            return new LoginResponse()
                    .setCode(200)
                    .setMsg("获取信息成功")
                    .setUser(userInfo)
                    .setRoles(rolesList)
                    .setPermissions(permissionsList);
        } catch (Exception e) {
            logger.error("获取用户信息失败", e);
            // 返回用户友好的错误信息，而不是抛出异常
            return new LoginResponse()
                .setCode(500)
                .setMsg("获取用户信息失败: " + e.getMessage());
        }
    }

    @PostMapping("/logout")
    public LoginResponse logout() {
        return new LoginResponse()
                .setCode(200)
                .setMsg("退出成功");
    }
} 